import api from '@/api/index.js';
import { onMounted, onBeforeUnmount, ref, watchEffect } from 'vue';

/**
 * 处理省市区
 * @param {ref(Object)} formData
 */
export default function(formData) {

	let fullRegionData = {}; // 完整的区域数据，以id为key，children为子级（原数据）
	let fullRegionList = []; // 完整的区域数据，child为子级
	let fullRegionTiled = {}; // 完整的区域数据，以id为key平铺开所有的数据
	const regionRange = ref([]); // 区域选择范围 [省<array>，市<array>，区<array>]
	const regionValue = ref([0, 0, 0]); // 区域选择索引
	const regionName = ref([]); // 区域选择数据（省、市、区）中文 [省:string，市:string，区:string]

	onMounted(() => {
		getRegion(); // 获取区域数据
		uni.$on('pagesC-address-add', handleReceiveData);
	});
	
	onBeforeUnmount(() => {
		uni.$off('pagesC-address-add', handleReceiveData);
	});

	// 获取完整的区域数据
	const getRegion = async () => {
		const res = await api.user_api.getArea();
		const data = res.data.data;
		fullRegionData = data;
		fullRegionList = formatRegionDataToList(data);
		fullRegionTiled = formatRegionDataToTiled(data);
		handleDisplay(); // 处理区域显示
	}

	// 格式化区域数据，将对象格式转成数组格式 [{id, name: '省', child: [{id, name: '市', child: [{id, name: '区'}] }] }, ...]
	const formatRegionDataToList = (regionData) => {
		const arr = [];
		for (let key in regionData) {
			if (regionData[key].children) {
				regionData[key].child = formatRegionDataToList(regionData[key].children);
			}
			arr.push(regionData[key]);
		}
		return arr;
	}

	// 格式化区域数据，以id为key平铺开所有的数据，用于快速查找 {id: {}, id: {}, ....}
	const formatRegionDataToTiled = (regionData, finallyData) => {
		finallyData = finallyData || {};
		for (let key in regionData) {
			finallyData[key] = regionData[key];
			if (regionData[key].children) {
				formatRegionDataToTiled(regionData[key].children, finallyData);
			}
		}
		return finallyData;
	}

	// 选择完所在地区
	const handleRegionChange = (e) => {
		const value = e.detail.value;
		regionValue.value = value;

		// 这里修改store数据
		formData.value.province_id = regionRange.value[0][value[0] || 0].id;
		formData.value.city_id = regionRange.value[1][value[1] || 0].id;
		formData.value.district_id = regionRange.value[2][value[2] || 0].id;

		regionName.value[0] = regionRange.value[0][value[0] || 0].name;
		regionName.value[1] = regionRange.value[1][value[1] || 0].name;
		regionName.value[2] = regionRange.value[2][value[2] || 0].name;
	}

	// 所在地区某列有改变时
	const handleRegionColumnChange = (e) => {
		const column = e.detail.column; // 列
		const index = e.detail.value; // 索引值
		const id = regionRange.value[column][index].id; // 滚动列选中的id

		regionValue.value[column] = index;

		if (column === 0) {
			regionValue.value[1] = 0;
			regionValue.value[2] = 0;
			regionRange.value[1] = filterOnlyIdAndName(fullRegionTiled[id].child);
			regionRange.value[2] = filterOnlyIdAndName(fullRegionTiled[id].child[0].child);
		} else if (column === 1) {
			regionValue.value[2] = 0;
			regionRange.value[2] = filterOnlyIdAndName(fullRegionTiled[id].child);
		}
	}

	// 处理接收地图定位的地址数据
	const handleReceiveData = (data) => {
		formData.value.province_id = '';
		formData.value.city_id = '';
		formData.value.district_id = '';

		regionName.value[0] = data.province;
		regionName.value[1] = data.city;
		regionName.value[2] = data.area;

		formData.value.address = data.address;

		handleDisplay();
	}

	// 处理区域显示
	const handleDisplay = () => {
		if (!Object.keys(fullRegionData).length) return;
		
		// 如果有省份id
		if (formData.value.province_id) {
			const provinceData = fullRegionTiled[formData.value.province_id]; // 找出省份数据
			regionRange.value[0] = filterOnlyIdAndName(fullRegionList);
			regionName.value[0] = provinceData.name;
			regionValue.value[0] = fullRegionList.findIndex(item => item === provinceData);
		}

		// 如果有市id
		if (formData.value.city_id && formData.value.province_id) {
			const cityData = fullRegionTiled[formData.value.city_id]; // 找出市数据
			regionRange.value[1] = filterOnlyIdAndName(fullRegionTiled[formData.value.province_id].child);
			regionName.value[1] = cityData.name;
			regionValue.value[1] = fullRegionTiled[formData.value.province_id].child.findIndex(item => item ===
				cityData);
		}

		// 如果有区县id
		if (formData.value.district_id && formData.value.province_id && formData.value.city_id) {
			const districtData = fullRegionTiled[formData.value.district_id]; // 找出区县数据
			regionRange.value[2] = filterOnlyIdAndName(fullRegionTiled[formData.value.city_id].child);
			regionName.value[2] = districtData.name;
			regionValue.value[2] = fullRegionTiled[formData.value.city_id].child.findIndex(item => item ===
				districtData);
		}

		// 如果有省份中文名称但没有id
		if (regionName.value[0] && !formData.value.province_id) {
			const provinceData = fullRegionList.find(item => item.name === regionName.value[0]); // 找出省份数据
			regionRange.value[0] = filterOnlyIdAndName(fullRegionList);
			formData.value.province_id = provinceData.id;
			regionValue.value[0] = fullRegionList.findIndex(item => item === provinceData);
		}

		// 如果有市中文名称但没有id
		if (regionName.value[1] && !formData.value.city_id && formData.value.province_id && regionRange.value[0]) {
			const cityData = fullRegionTiled[formData.value.province_id].child.find(item => item.name === regionName
				.value[1]); // 找出市数据
			regionRange.value[1] = filterOnlyIdAndName(fullRegionTiled[formData.value.province_id].child);
			formData.value.city_id = cityData.id;
			regionValue.value[1] = fullRegionTiled[formData.value.province_id].child.findIndex(item => item ===
				cityData);
		}

		// 如果有区县中文名称但没有id
		if (regionName.value[2] && !formData.value.district_id && regionRange.value[1] && formData.value.city_id &&
			formData.value.province_id && regionRange.value[0]) {
			const districtData = fullRegionTiled[formData.value.city_id].child.find(item => item.name === regionName
				.value[2]); // 找出市数据
			regionRange.value[2] = filterOnlyIdAndName(fullRegionTiled[formData.value.city_id].child);
			formData.value.district_id = districtData.id;
			regionValue.value[2] = fullRegionTiled[formData.value.city_id].child.findIndex(item => item ===
				districtData);
		}

		// 如果以上都没有，默认取第一个省市区数据
		if (!regionName.value.length) {
			regionRange.value[0] = filterOnlyIdAndName(fullRegionList);
			regionRange.value[1] = filterOnlyIdAndName(fullRegionList[0].child);
			regionRange.value[2] = filterOnlyIdAndName(fullRegionList[0].child[0].child);
		}
	}

	// 筛选出id和name
	const filterOnlyIdAndName = (arr) => {
		return arr.map(item => {
			return {
				id: item.id,
				name: item.name,
			}
		})
	}
	
	// 定位页面
	const handleNavToLocationPage = () => {
		uni.navigateTo({
			url: '/pages/location/index?emit=pagesC-address-add'
		});
	}

	return { regionRange, regionValue, regionName, handleRegionColumnChange, handleRegionChange, handleNavToLocationPage, handleDisplay };
}